<template>
  <div class="categories">
    <div class="main">
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- button按钮 -->
      <el-row style="margin-top:15px">
        <el-button type="primary" plain @click="getParentCateFn">添加分类</el-button>
      </el-row>
      <div class="main-worp" style="margin-top:15px">
        <!--表格  -->
        <el-table :data="cateData.result" style="width: 100%" row-key="cat_id" lazy :load="load" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column label="商品ID" prop="cat_name"></el-table-column>
          <el-table-column label="商品名称" prop="cat_level" :formatter="statusFormatter"></el-table-column>
          <el-table-column label="是否有效" prop="cat_deleted">有效</el-table-column>
          <el-table-column label="操作">  
            <template #default="scope"> 
              <el-button type="primary" icon="el-icon-edit" circle @click="cateDialog(scope.row)"></el-button>
              <el-button type="danger" icon="el-icon-delete" circle @click="delectCateFn(scope.row.cat_id)"></el-button> 
            </template>                                 
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          v-model:currentPage="params.pagenum"
          :page-sizes="[10, 15, 20, 30]"
          :page-size="params.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="cateData.total"
        >
        </el-pagination>
      </div>
      <!-- 添加分类 -->
      <el-dialog v-model="addCateDialog" title="添加分类" width="30%">
        <el-form :model="cateInfoForm" ref="cateInFormRef">
          <el-form-item label="分类名" :label-width="formLabelWidth" prop="cat_name" :rules="rules"> 
            <el-input v-model="cateInfoForm.cat_name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="分类" :label-width="formLabelWidth">
            <el-cascader :options="cateObj.cateList" :props="cateOptions" v-model="cateObj.cate" @change="handleChange"></el-cascader>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="addCateFn">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 修改商品分类 -->
      <el-dialog v-model="editCateDialog" title="修改商品分类" width="30%">
        <el-form :model="cateForm">
            <el-form-item>
              <el-input v-model="cateForm.cat_name" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="editCateFn()">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
   
</template>

<script>
import { ElMessageBox } from 'element-plus'
import { reactive ,getCurrentInstance,onMounted,ref} from 'vue'
import {getCate,addCate,getParentCate,editCate,delectCate} from "../../http/api"
import { useRouter } from "vue-router";
export default {
  setup() {
    var addCateDialog = ref(false);
    const {proxy}=getCurrentInstance()
    const router = useRouter();
    let cateData = reactive({});
    let params = reactive({
      pagenum: router.pagenum || 1,
      pagesize: router.pagesize ||30,
      query: router.query || "",
      type:3
    });
    const rules = reactive({
      required: true, message: '请输入分类名', trigger: 'blur' 
    })
    const cateObj = reactive({
      cateList:[],
      cate:[]

    });
    const cateOptions = reactive({
      value: "cat_id",
      label: "cat_name",
      children: "children"
    });
    // 分类列表
    const cateInfoForm = reactive({
      cat_name: "",
      cat_level:2,
      cat_pid: ''
    });
    const cateInForm = ref();
    // 编辑
    const editCateDialog = ref(false);   
    let cateForm = reactive ({
      cat_id:'',
      cat_name:''
    });
    const cateInFormRef = ref();
    // 获取商品分类列表
    const getCateFn = async () => {
      const res = await getCate(params);
      Object.assign(cateData, res);
    };    
    onMounted(() => {
      getCateFn();
    });
    // 级别
    const statusFormatter = (row) =>{
      const cat_level = row.cat_level
      if (cat_level == 0) {
        return '一级'
      } else if (cat_level == 1) {
        return '二级'
      } else if (cat_level == 2) {
        return '三级'
      }
    };
    // 每页显示的条数发生变化时触发
    const handleSizeChange=(val)=>{
      params.pagesize=val
      router.push({
        query:Object.assign({},router.query,{
          query:params.query
        })       
      })
      getCateFn();
    };
    // 页码发生变化时触发
    const  handleCurrentChange=(val)=>{
      params.pagenum=val
      router.push({
        query:Object.assign({},router.query,{
          query:params.query
        })
      })
      getCateFn();
    };
     //添加分类 弹出框
    const getParentCateFn = async() =>{
      console.log("1111")
      addCateDialog.value = true
      const res = await getParentCate({ type: 2 })
      cateObj.cateList=res
    }
    // 提交添加
    const addCateFn = () => {
      // validate 检验表单的内容是否合法
      proxy.$refs.cateInFormRef.validate(async (valid) => {
        if (valid) {
          await addCate(cateInfoForm);
          addCateDialog.value = false
          //  resetFields	对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
          proxy.$refs.cateInFormRef.resetFields();
          getCateFn();
        }
      });     
    }; 
    onMounted(() => {
      getParentCate();
    });

    const handleChange = (value) =>{
      console.log(value);
      cateInfoForm.cat_pid=value[1];
    };

    // 修改商品分类 回显信息
    const cateDialog = async (row) => {
      editCateDialog.value = true;
      const {cat_id,cat_name} = row;
      cateForm.cat_id=cat_id;
      cateForm.cat_name=cat_name;
    };
    // 点击编辑提交
    const editCateFn = async () => {
      const {cat_id,cat_name} = cateForm;
      await editCate(cat_id, {cat_name});
      editCateDialog.value = false;
      getCateFn();
    };
    // 删除
    const delectCateFn = (id) => {
      ElMessageBox.confirm(
        "此操作将永久删除该商品分类, 是否继续?", "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async() => {
           await delectCate(id);
         getCateFn()
          
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消删除",
          });
        });
    };

    return {
      cateData,
      params,
      getCateFn,
      statusFormatter,
      handleSizeChange,
      handleCurrentChange,
      editCateDialog,
      cateForm,
      cateDialog,
      editCateFn,
      delectCateFn,
      addCateFn,
      cateInForm,
      cateInFormRef,
      cateOptions,
      getParentCateFn,
      addCateDialog,
      cateInfoForm,
      cateObj,
      handleChange,
      addCateFn,
      rules
    }
  }

}
</script>

<style lang="scss" scoped>
.categories {
  background-color: #eee;
  overflow: hidden;
  padding: 20px;
  .main {
    background-color: #fff;
    padding: 20px;
    .main-worp {
      overflow-x: auto;
      height: calc(100vh - 180px);
    }
  }
}
</style>

